package com.itcs.box.server.resolver;

import com.alibaba.fastjson.JSON;
import com.itcs.box.domain.BoxData;
import com.itcs.box.domain.BoxRequest;
import com.itcs.box.domain.BoxResponse;
import com.itcs.box.server.callback.BoxCallBack;
import com.itcs.box.server.server.BoxToAppService;
import com.itcs.box.server.server.NettyChannelMap;
import com.itcs.box.util.LogUtils;
import com.itcs.eureka.service.PayApiFeignClientService;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 功能描述:
 * <登录解析类>
 *
 * @ClassName: Box1001Resolver
 * @Author: wanghui
 * @Date: 2019年05月17日 09:36:39
 *
 * @Copyright: 2019 Inc. All rights reserved. 注意: 本内容仅限于内部传阅,禁止外泄以及用于其他的商业目
 */
@Component
@SuppressWarnings("all")
public class Box1001Resolver extends BoxToAppService implements MsgResolverAdapter {

	private ExecutorService executorService = Executors.newFixedThreadPool(10);

	private Log logger = LogFactory.getLog(getClass());

	@Resource(name="payApiRest")
	private PayApiFeignClientService apiService;

	@Override
	public boolean support(BoxRequest boxRequest) {
		return "1001".equals(boxRequest.getMessgeType());
	}

	@Override
	public void resolve(final ChannelHandlerContext channelHandlerContext, BoxRequest boxRequest) {

		BoxData data = boxRequest.getData();
		String deviceId = data.getDeviceId();

		ChannelHandlerContext oldChannel = NettyChannelMap.get(deviceId);

		if (oldChannel != null) {
			if (channelHandlerContext != oldChannel) {
				// 如果两个通道不是同一个
				try {
					logger.warn(LogUtils.build("1001", "通讯盒登录",
							"通讯盒:" + deviceId + ",已登录连接与当前通道不一致，强制关闭老的连接",
							JSON.toJSONString(boxRequest)));
					oldChannel.disconnect();
					oldChannel.close();
				} catch (Exception e) {
					logger.error("强制关闭netty连接异常", e);
				}
			}
		}

		logger.info(LogUtils.build("1001", "通讯盒登录",
				"通讯盒:" + boxRequest.getData().getDeviceId(),
				JSON.toJSONString(boxRequest)));

		Send2AppThread appThread = new Send2AppThread(
				apiService,
				serverId,
				channelHandlerContext,
				boxRequest,
				new BoxCallBack() {
			@Override
			public void callback(BoxResponse boxResponse) {
				String result = boxResponse.getData().getResult();
				String deviceId = boxResponse.getData().getDeviceId();
				String channelId = boxResponse.getChannelId();
				// 清除channelId,防止返回给盒子
				boxResponse.setChannelId(null);
				if ("1".equals(result)) {
					logger.info(LogUtils.build(
							"1001",
							"通讯盒登录",
							"通讯盒:" + deviceId + " 登录验证成功"));
					NettyChannelMap.add(deviceId, channelId, channelHandlerContext);
				} else {
					try {
						channelHandlerContext.disconnect();
						channelHandlerContext.close();
					} catch (Exception e) {
						logger.error("强制关闭netty连接异常", e);
					}
					logger.warn(LogUtils.build(
							"1001",
							"通讯盒登录",
							"通讯盒:" + deviceId + " 登录验证失败,断开连接,result:" + result));
				}
			}
		});

		executorService.execute(appThread);

	}

}
